
import yaml

from configs import setting


# 读取
def read_yaml(key):
    with open(setting.extract_name,"r",encoding="utf-8") as f:
        value = yaml.safe_load(f)
        return value[key]

# 读取所有值
def read_all():
    with open(setting.extract_name,"r",encoding="utf-8") as f:
        value = yaml.safe_load(f)
        return value

# 写入:追加
def write_yaml(data):
    with open(setting.extract_name, encoding='utf-8',mode = "a+") as f:
        yaml.safe_dump( data = data,stream=f,allow_unicode=True)

# 清空
def clear_yaml():
    with open(setting.extract_name, encoding='utf-8',mode = "w") as f:
        f.truncate()

#
# # 更新YAML文件中的嵌套字段
# def update_yaml_field(yml_path, field_path, value):
#     """更新YAML文件中的嵌套字段（支持数字类型）"""
#     data = read_yaml(yml_path) or []
#
#     current = data
#     for i, key in enumerate(field_path[:-1]):
#         if isinstance(key, int) and isinstance(current, list):
#             while key >= len(current):
#                 current.append({})
#             current = current[key]
#         elif isinstance(current, dict):
#             current = current.setdefault(key, {})
#         else:
#             current = {key: {}}
#             data = current
#
#     # 设置最终值（保持原始类型）
#     current[field_path[-1]] = value  # 不强制转换为字符串
#
#     # 写回文件
#     with open(yml_path, "w", encoding="utf-8") as f:
#         yaml.dump(data, f, allow_unicode=True, default_flow_style=False)
#
#
# # 支持列表索引操作
# def update_list_item(yml_path, list_path, index, value):
#     """更新YAML列表中的指定项（如 test_cases.0.request.url）"""
#     data = read_yaml(yml_path)
#     current = data
#     for key in list_path[:-1]:
#         current = current[key]
#     current[list_path[-1]][index] = value
#     # 写入更新后的数据
